//
//  UIViewControllerUtils.swift
//
//  Created by ink on 2024/6/28.
//  Copyright © 2024 ZM. All rights reserved.
//

import Foundation
import UIKit

extension UIViewController {
    
    public func currentVC() -> UIViewController? {
        if let presentVC = presentedViewController {
            return presentVC.currentVC()
        }
        else if let tabVC = self as? UITabBarController {
            if let selectVC = tabVC.selectedViewController {
                return selectVC.currentVC()
            }
            return nil
        }
        else if let navVC = self as? UINavigationController {
            return navVC.visibleViewController?.currentVC()
        }
        else {
            return self
        }
    }
    
    public var topVC: UIViewController? {
        if let presentVC = presentedViewController {
            return presentVC.topVC
        }else if let tabVC = self as? UITabBarController {
            return tabVC.selectedViewController?.topVC
        } else if let naiVC = self as? UINavigationController {
            return naiVC.visibleViewController?.topVC
        }
        return self
    }
}

public extension UIApplication {
    /// 获取当前 App 中显示在最前面的 ViewController，兼容 iOS 13+
    func topMostViewController(base: UIViewController? = UIApplication.shared.getKeyWindow()?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topMostViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            return topMostViewController(base: tab.selectedViewController)
        }
        if let presented = base?.presentedViewController {
            return topMostViewController(base: presented)
        }
        return base
    }
    
    /// 安全获取当前主窗口，兼容 iOS 13+
    func getKeyWindow() -> UIWindow? {
        if #available(iOS 15.0, *) {
            return self.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .flatMap { $0.windows }
                .first { $0.isKeyWindow }
        } else {
            return self.windows.first { $0.isKeyWindow }
        }
    }
}
